# -*- coding: utf-8 -*-
"""
Created on Otc. 29 10:30:42 2019
version:v1.0
@author: Binary
"""
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver import ActionChains
import selenium.webdriver.common.keys as ks
from selenium.webdriver.support import expected_conditions as EC
from urllib import request
import time
import os
import traceback
################################################
# 功能：webdriver 封装
# 前提：安装selenium，并且有 webdriver 驱动
# author：二进制
################################################
driver = None

keys = {}
for name, value in vars(ks.Keys).items():
    keys[name] = value


def parseKey(key):
    if key in keys.keys():
        return keys[key]
    else:
        return key


def parseKeys(key):
    if isinstance(key, str):
        return key.split(',')
    else:
        return key

bools = {"True": True, "False": False}


def parseBool(boolean):
    if isinstance(boolean, str):
        return bools[boolean]
    else:
        return boolean


def getDriver(web="chrome"):
    global driver
    if web == "chrome":
        driver = webdriver.Chrome()
    elif web == "IE":
        driver = webdriver.Ie()
    elif web == '360':
        driver = webdriver.Chrome()
    else:
        driver = webdriver.Chrome()
    driver.implicitly_wait(10)
    return driver


def openWeb(url):
    # 登陆
    driver.get(url)
    driver.implicitly_wait(10)
    # 窗口最大化
    try:
        driver.maximize_window()
    except:
        pass


def openNext(url, s="1"):
    js='window.open("%s");' % url
    driver.execute_script(js)
    handles = driver.window_handles
    driver.switch_to_window(handles[len(handles)-1])
    wait(s)
    okAlert()
    driver.implicitly_wait(10)
    # 窗口最大化
    for i in range(3):
        try:
            driver.maximize_window()
        except:
            pass


def forceMax():
    try:
        js='if(window.screen){var myw = screen.availWidth;var myh=screen.availHeight;window.moveTo(0,0);window.resizeTo(myw,myh);}'
        driver.execute_script(js)
    except:
        pass

def tryEnter(s="1"):
    try:
        driver.get("javascript:document.getElementById('overridelink').click();")#解决IE提示问题
        wait(s)
    except:
        pass


def gotoWin(index="-1", s="1"):
    handles = driver.window_handles
    driver.switch_to_window(handles[int(index)])
    wait(s)
    # 窗口最大化
    try:
        driver.maximize_window()
    except:
        pass


# 判断页面上的xpath是否存在
def is_element_exists(xpath, id_flag=False, wait_times="2", s="1"):
    for i in range(int(wait_times)):
        try:
            if parseBool(id_flag):
                driver.find_element_by_id(xpath)
            else:
                driver.find_element_by_xpath(xpath)
            return True
        except Exception as e:
            # print("Excpetion:[%s][%s]" % (e, traceback.format_exc()))
            print('%s.do not find the node,wait %s second(s)' % (i, s))
            wait(s)
    return False


def clickNode(xpnode, double_click=True, id_flag=False):
    # 判断页面上的xpath是否存在
    if is_element_exists(xpnode, id_flag):
        # 查找第一个trans节点，单击
        if parseBool(id_flag):
            trans = driver.find_element_by_id(xpnode)
        else:
            trans = driver.find_element_by_xpath(xpnode)
        action = ActionChains(driver)
        if parseBool(double_click):
            action.double_click(trans).perform()
        else:
            action.click(trans).perform()
    else:
        print("do not find the [%s] node!" % xpnode)
    time.sleep(0.5)


def clickButton(xpnode, id_flag=False):
    if is_element_exists(xpnode, id_flag):
        if parseBool(id_flag):
            driver.find_element_by_id(xpnode).click()
        else:
            driver.find_element_by_xpath(xpnode).click()
    else:
        print("do not find the [%s] node!" % xpnode)
    time.sleep(0.2)


def setText(xpnode, v_text, id_flag=False):
    if is_element_exists(xpnode, id_flag):
        if parseBool(id_flag):
            driver.find_element_by_id(xpnode).clear()
            driver.find_element_by_id(xpnode).send_keys(v_text)
        else:
            driver.find_element_by_xpath(xpnode).clear()
            driver.find_element_by_xpath(xpnode).send_keys(v_text)
    else:
        print("do not find the [%s] node!" % xpnode)


def upload(xpnode, v_file, id_flag):
    setText(xpnode, v_file,id_flag)


def checkText(xpnode, v_text, id_flag=False):
    if parseBool(id_flag):
        if driver.find_element_by_id(xpnode).text == v_text:
            return True
        else:
            return False
    else:
        if driver.find_element_by_xpath(xpnode).text == v_text:
            return True
        else:
            return False


def clickKey(xpnode, v_key, id_flag=False):
    if is_element_exists(xpnode, id_flag):
        if parseBool(id_flag):
            trans = driver.find_element_by_id(xpnode)
        else:
            trans = driver.find_element_by_xpath(xpnode)
        action = ActionChains(driver)
        action.click(trans).send_keys(parseKey(v_key)).perform()
    else:
        print("do not find the [%s] node!" % xpnode)


def clickKeys(xpnode, v_keys, id_flag=False):
    if is_element_exists(xpnode, id_flag):
        if parseBool(id_flag):
            trans = driver.find_element_by_id(xpnode)
        else:
            trans = driver.find_element_by_xpath(xpnode)
        action = ActionChains(driver)
        action.click(trans)
        for key in parseKeys(v_keys):
            action.send_keys(parseKey(key))
        action.perform()
    else:
        print("do not find the [%s] node!" % xpnode)


def pressKeys(v_keys, s="1"):
    action = ActionChains(driver)
    for key in parseKeys(v_keys):
        action.send_keys(parseKey(key))
        action.perform()
        wait(s)


def moveTo(xpnode, id_flag=False):
    if is_element_exists(xpnode, id_flag):
        if parseBool(id_flag):
            trans = driver.find_element_by_id(xpnode)
        else:
            trans = driver.find_element_by_xpath(xpnode)
        action = ActionChains(driver)
        action.move_to_element(trans).perform()
    else:
        print("do not find the [%s] node!" % xpnode)


def switchTo(frame=None):
    if frame:
        driver.switch_to.frame(frame)
    else:
        driver.switch_to.default_content()


def savePic(xpnode, v_path, v_name, id_flag=False):
    if is_element_exists(xpnode, id_flag):
        clickNode(xpnode, False, id_flag)
        image_url = driver.current_url
        if not os.path.exists(v_path):
                os.makedirs(v_path)
        req = request.Request(image_url, headers={'User-Agent':  r'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:45.0) Gecko/20100101 Firefox/45.0'})
        data = request.urlopen(req, timeout=30).read()
        f = open("%s/%s" % (v_path, v_name), 'wb')
        f.write(data)
        f.close()
    else:
        print("do not find the [%s] node!" % xpnode)


def savePicbysrc(xpnode, v_path, v_name, id_flag=False):
    if is_element_exists(xpnode, id_flag):
        if parseBool(id_flag):
            trans = driver.find_element_by_id(xpnode)
        else:
            trans = driver.find_element_by_xpath(xpnode)
        print(trans.get_attribute('src'))
        image_url = trans.get_attribute('src')
        if not os.path.exists(v_path):
                os.makedirs(v_path)
        req = request.Request(image_url, headers={'User-Agent':  r'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:45.0) Gecko/20100101 Firefox/45.0'})
        data = request.urlopen(req, timeout=30).read()
        f = open("%s/%s" % (v_path, v_name), 'wb')
        f.write(data)
        f.close()
    else:
        print("do not find the [%s] node!" % xpnode)


def wait(s="1"):
    if float(s) < 5.0:
        time.sleep(float(s))
    else:
        m = float(s) % 5
        n = int(float(s)/5)
        for i in range(n):
            print("last %s seconds" % ((n-i) * 5 + m))
            time.sleep(5)
        time.sleep(m)


def okAlert(s="1"):
    if EC.alert_is_present:
        try:
            print("Alert exists")
            alert=driver.switch_to_alert()
            # print (alert.text)
            alert.accept()
            print("Alert accepted")
            wait(s)
        except Exception as e:
            # print("Excpetion:[%s][%s]" % (e, traceback.format_exc()))
            # print("error")
            pass
    else:
        print("NO alert exists")


def closeDriver():
    try:
        handles = driver.window_handles
        for handle in handles:
            try:
                driver.switch_to_window(handle)
                driver.close()
            except:
                pass
    except:
        pass
